#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <filesystem>
#include <mutex>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <memory>
#include <time.h>

namespace LogModule
{

    // 获取当前时间
    std::string CurrentTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr); // 时间戳

        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d:%02d:%02d:%02d",
                 curr.tm_year+1900,
                 curr.tm_mon+1,
                 curr.tm_mday,
                 curr.tm_hour,
                 curr.tm_min,
                 curr.tm_sec);
        return buffer;
    }
    // 构成：1.构建日志字符串 2.刷新磁盘
    const std::string defaultlogpath = "./log/";
    const std::string defaultlogname = "log.txt";

    // 日志等级
    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARING,
        ERROR,
        FATAL
    };
    std::string LevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARING:
            return "WARING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "None";
        }
    }
    // 3.刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    class ConsoleStrategy : public LogStrategy
    {
    public:
        ConsoleStrategy()
        {
        }
        ~ConsoleStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            std::lock_guard<std::mutex> lock(_lock);
            std::cout << message << std::endl;
        }

    private:
        std::mutex _lock;
    };

    class FileStrategy : public LogStrategy
    {
    public:
        FileStrategy(const std::string &logpath = defaultlogpath,
                     const std::string &logname = defaultlogname)
            : _logpath(logpath), _logname(logname)
        {
            /// 确定_logpath是否存在
            if (std::filesystem::exists(_logpath))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << std::endl;
            }
        }
        ~FileStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            std::lock_guard<std::mutex> lock(_lock);
            std::string log = _logpath + _logname;
            int fd = ::open(log.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0600); // 日志写入，追加模式
            if (fd == -1)
            {
                std::cerr << "open fail" << std::endl;
                return;
            }
            size_t n = ::write(fd, message.c_str(), message.size());
            if (n == -1)
            {
                std::cerr << "write fail" << std::endl;
                return;
            }
            close(fd);
        }

    private:
        std::string _logpath;
        std::string _logname;

        std::mutex _lock;
    };

    // 日志类，构建字符串,根据策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            // 默认
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileStrategy>();
        }
        ~Logger()
        {
        }
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, int line, Logger &logger)
                : _currtime(CurrentTime()),
                  _level(level),
                  _pid(::getpid()),
                  _filename(filename),
                  _line(line),
                  _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "]" << "[" << LevelToString(_level) << "]" << "[" << _pid << "]" << "[" << _filename << "]" << "[" << _line << "]";
                _loginfo = ssbuffer.str();
            }

            //*********
            template <class T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                _logger._strategy->SyncLog(_loginfo);
            }

        private:
            std::string _currtime; // 当前日志时间
            LogLevel _level;       // 日志等级
            pid_t _pid;            // 进程
            std::string _filename; // 源文件名称
            uint32_t _line;        // 日志所在行号
            Logger &_logger;
            std::string _loginfo; // 一条完整日志记录
        };
        LogMessage operator()(LogLevel level, const std::string &filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy;
    };

    Logger logger;

#define LOG(Level) logger(Level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog()
#define ENABLE_FILE_LOG() logger.EnableFileLog()
}